package com.googlecode.stemwijzer.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.stemwijzer.client.StemwijzerService;
import com.googlecode.stemwijzer.shared.NameValidator;
import com.googlecode.stemwijzer.shared.model.AnswerQuestionCommand;
import com.googlecode.stemwijzer.shared.model.Questionnaire;

@SuppressWarnings("serial")
public class StemwijzerServiceImpl extends RemoteServiceServlet implements StemwijzerService {

	private String userName = null;
	private Questionnaire questionnaire = null;

	@Override
	public Questionnaire registerUser(String userName) {
		if (!NameValidator.isValid(userName)) {
			return null;
		}
		this.userName = userName;
		this.questionnaire = new Questionnaire(userName);

		sleep(1000);

		return this.questionnaire;
	}

	@Override
	public Boolean sendAnswer(AnswerQuestionCommand command) {
		if (this.questionnaire == null) {
			return false;
		}
		if (command == null || command.getQuestion() == null || command.getAnswer() == null) {
			return false;
		}

		this.questionnaire.setAnswer(command.getQuestion(), command.getAnswer());

		sleep(500);

		return true;
	}

	@Override
	public Questionnaire getQuestionnaire() {
		if (questionnaire == null) {
			return null;
		}
		return questionnaire;
	}

	private void sleep(final int milliseconds) {
		try {
			System.out.println("Zzz...");

			Thread.sleep(milliseconds);
		} catch (InterruptedException e) {
		}
	}

	@Override
	public Questionnaire resetSession() {
		if (this.userName == null) {
			return null;
		}
		this.questionnaire = new Questionnaire(userName);

		sleep(1000);

		return this.questionnaire;
	}
}
